package com.pxmeta.party.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pxmeta.audio.entity.Music;
import com.pxmeta.audio.service.IMusicService;
import com.pxmeta.party.entity.PartyMusicChoose;
import com.pxmeta.party.entity.dto.MusicChooseDTO;
import com.pxmeta.party.mapper.PartyMusicChooseMapper;
import com.pxmeta.party.service.IPartyMusicChooseService;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PartyMusicChooseServiceImpl extends ServiceImpl<PartyMusicChooseMapper, PartyMusicChoose> implements IPartyMusicChooseService {

    private final IMusicService musicService;

    private final IUserService userService;


    @Override
    public void chooseMusic(Long userId, Long partyId, Long musicId) {
        PartyMusicChoose partyMusicChoose = new PartyMusicChoose();
        partyMusicChoose.setPartyId(partyId);
        partyMusicChoose.setMusicId(musicId);
//        partyMusicChoose.setIsCurrent(false);
        partyMusicChoose.setUserId(userId);
        this.save(partyMusicChoose);
    }

    @Override
    public List<MusicChooseDTO> getChooseMusicList(Long partyId) {

        LambdaQueryWrapper<PartyMusicChoose> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PartyMusicChoose::getPartyId, partyId)
                .orderByAsc(PartyMusicChoose::getCreateTime);

        List<PartyMusicChoose> list = this.list(wrapper);
        List<MusicChooseDTO> finalList = Lists.newLinkedList();

        List<Long> musicIds = list.stream().map(PartyMusicChoose::getMusicId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(musicIds)){
            return Lists.newArrayList();
        }



        for (PartyMusicChoose partyMusicChoose : list) {
            Long musicId = partyMusicChoose.getMusicId();
            Long userId = partyMusicChoose.getUserId();
            MusicChooseDTO dto = new MusicChooseDTO();
            User user = userService.getById(userId);
            Music music = musicService.getById(musicId);
            BeanUtils.copyProperties(music, dto);
            dto.setMusicChooseId(partyMusicChoose.getId());
            dto.setNickname(user.getNickname());
            dto.setUsername(user.getUsername());
            finalList.add(dto);
        }

        return finalList;

    }
}
